<template>
  <div class="system-view">
    <div class="header">
      <h1>系统设置</h1>
    </div>

    <el-card class="config-card">
      <template #header>
        <div class="card-header">
          <span>微信联系配置</span>
          <el-button type="primary" @click="handleSave" :loading="saving">保存配置</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="configForm"
        :rules="rules"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="微信号" prop="contact_wechat_id">
          <el-input
            v-model="configForm.contact_wechat_id"
            placeholder="请输入微信号"
            clearable
          />
          <div class="form-tip">用户在小程序结算时显示的微信号</div>
        </el-form-item>

        <el-form-item label="微信二维码" prop="contact_wechat_qr_url">
          <div class="qr-upload">
            <el-upload
              class="qr-uploader"
              :action="uploadAction"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleQrSuccess"
              :on-error="handleQrError"
              :before-upload="beforeQrUpload"
              name="file"
              accept="image/*"
            >
              <img v-if="configForm.contact_wechat_qr_url" :src="getImageUrl(configForm.contact_wechat_qr_url)" class="qr-image" />
              <el-icon v-else class="qr-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="qr-actions" v-if="configForm.contact_wechat_qr_url">
              <el-button size="small" @click="handlePreviewQr">预览</el-button>
              <el-button size="small" type="danger" @click="handleRemoveQr">删除</el-button>
            </div>
          </div>
          <div class="form-tip">建议上传正方形二维码图片，支持 JPG、PNG 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item label="引导文案" prop="contact_tip_text">
          <el-input
            v-model="configForm.contact_tip_text"
            type="textarea"
            :rows="4"
            placeholder="请输入引导用户添加微信的文案"
            maxlength="500"
            show-word-limit
          />
          <div class="form-tip">在小程序结算弹层中显示的引导文案，支持换行</div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 二维码预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="二维码预览"
      width="400px"
      center
    >
      <div class="qr-preview">
        <img :src="getImageUrl(configForm.contact_wechat_qr_url)" alt="微信二维码" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

// 响应式数据
const saving = ref(false)
const previewVisible = ref(false)
const formRef = ref()

const configForm = reactive({
  contact_wechat_id: '',
  contact_wechat_qr_url: '',
  contact_tip_text: ''
})

// 表单验证规则
const rules = {
  contact_wechat_id: [
    { required: true, message: '请输入微信号', trigger: 'blur' }
  ],
  contact_tip_text: [
    { required: true, message: '请输入引导文案', trigger: 'blur' }
  ]
}

// 上传配置
const uploadAction = ref(`${import.meta.env.VITE_API_BASE_URL}/upload/image`)
const uploadHeaders = ref({
  'Authorization': `Bearer ${authStore.token}`
})

// 获取配置
const fetchConfigs = async () => {
  try {
    const response = await request.get('/system/configs', {
      params: { keys: 'contact_wechat_id,contact_wechat_qr_url,contact_tip_text' }
    })

    const configs = response.data
    configForm.contact_wechat_id = configs.contact_wechat_id?.value || 'jewelry_store_2024'
    configForm.contact_wechat_qr_url = configs.contact_wechat_qr_url?.value || '/static/images/wechat-qr.jpg'
    configForm.contact_tip_text = configs.contact_tip_text?.value || '我们已记录您的选购信息，添加客服微信即可继续沟通付款'
  } catch (error) {
    ElMessage.error('获取配置失败')
  }
}

// 保存配置
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    const configs = {
      contact_wechat_id: {
        value: configForm.contact_wechat_id,
        description: '微信联系号'
      },
      contact_wechat_qr_url: {
        value: configForm.contact_wechat_qr_url,
        description: '微信二维码图片URL'
      },
      contact_tip_text: {
        value: configForm.contact_tip_text,
        description: '微信联系引导文案'
      }
    }

    await request.put('/system/configs', { configs })
    ElMessage.success('配置保存成功')
  } catch (error) {
    if (error !== 'validation failed') {
      ElMessage.error('配置保存失败')
    }
  } finally {
    saving.value = false
  }
}

// 二维码上传成功
const handleQrSuccess = (response: any) => {
  if (response.success) {
    configForm.contact_wechat_qr_url = response.data.url
    ElMessage.success('二维码上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 二维码上传失败
const handleQrError = () => {
  ElMessage.error('二维码上传失败')
}

// 上传前检查
const beforeQrUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 预览二维码
const handlePreviewQr = () => {
  previewVisible.value = true
}

// 删除二维码
const handleRemoveQr = async () => {
  try {
    await ElMessageBox.confirm('确定要删除当前二维码吗？', '确认删除')
    configForm.contact_wechat_qr_url = ''
    ElMessage.success('二维码已删除')
  } catch (error) {
    // 用户取消
  }
}

// 获取图片完整URL
const getImageUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `${import.meta.env.VITE_API_BASE_URL}${url}`
}

onMounted(() => {
  fetchConfigs()
})
</script>

<style scoped>
.system-view {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.config-card {
  max-width: 800px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.qr-upload {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.qr-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qr-uploader:hover {
  border-color: #409eff;
}

.qr-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.qr-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.qr-actions {
  display: flex;
  gap: 10px;
}

.qr-preview {
  text-align: center;
}

.qr-preview img {
  max-width: 100%;
  max-height: 300px;
}
</style>
